package com.sinodata.bsm.cicp.collector.windows;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CollectorUtil;
import com.sinodata.bsm.cicp.util.FileAttribute;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class WinFileSchedule extends Collector {
    private static int TIMEOUT = 300;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        //        String path = this.getParamMap().get("文件目录").trim();
        //        String fileName = this.getParamMap().get("文件格式").trim();
        String path = this.getParamMap().get("FileDirectory").trim();
        String fileName = this.getParamMap().get("FileFormat").trim();
        List<ResPropertyValue> result = new ArrayList<ResPropertyValue>();
        ResPropertyValue value = new ResPropertyValue();
        String[] propMetas = this.getPropMeta();
        ResPropertyValue.PropValue[] propValue = new ResPropertyValue.PropValue[propMetas.length];
        FileAttribute currentAttribute = CollectorUtil.getNewestRemoteFileByPatternWin(path, fileName, ip);
        if (currentAttribute == null) {
            propValue[0] = ResPropertyValue.createPropValue("N/A", propMetas[0]);
            propValue[1] = ResPropertyValue.createPropValue("", propMetas[1]);
            propValue[2] = ResPropertyValue.createPropValue("", propMetas[2]);
            propValue[3] = ResPropertyValue.createPropValue("0", propMetas[3]);
            value.setValues(propValue);
            result.add(value);
            return result;
        }

        String[] arr = new String[4];
        //文件名
        arr[0] = getFileName(currentAttribute.name, path);
        //文件最后修改时间
        String fileTime = currentAttribute.lastModification;
        arr[1] = "" + getDateMillisForCMD(fileTime.trim());
        //远端机器时间,采集时间
        //        arr[2] = "" + getRemoteCurrentTimeMillis(ip);
        arr[2] = "" + getRemoteCurrentTime(ip);
        //文件大小
        arr[3] = currentAttribute.size + "";

        propValue[0] = ResPropertyValue.createPropValue(arr[0], propMetas[0]);
        propValue[1] = ResPropertyValue.createPropValue(arr[1], propMetas[1]);
        propValue[2] = ResPropertyValue.createPropValue(arr[2], propMetas[2]);
        propValue[3] = ResPropertyValue.createPropValue(arr[3], propMetas[3]);
        value.setValues(propValue);
        result.add(value);
        return result;

    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "FileDirectory", "FileFormat" };
    }

    private String getFileName(String fullName, String path) {
        fullName = fullName.trim();
        path = path.trim();
        if (path.endsWith("\\"))
            fullName = fullName.substring(path.length());
        else
            fullName = fullName.substring(path.length() + 1);
        return fullName;
    }

    private long getDateMillisForCMD(String date) {
        Calendar calendar = Calendar.getInstance();
        int i = Integer.parseInt(date.substring(0, 4));
        calendar.set(Calendar.YEAR, i);
        i = Integer.parseInt(date.substring(4, 6));
        calendar.set(Calendar.MONTH, i - 1);
        i = Integer.parseInt(date.substring(6, 8));
        calendar.set(Calendar.DAY_OF_MONTH, i);
        i = Integer.parseInt(date.substring(8, 10));
        //在Windows的GetNewesRemoteFileInfo.exe取出的时间是格林威治时间0:00的时间
        //北京时间是东八区,所以需要加8小时.
        //本来应该在此可执行程序中加,不过小弟的c语言十分汗颜不会加就加在这里了
        //Modify by Credible_zhang at 200604021242
        calendar.set(Calendar.HOUR_OF_DAY, i + 8);
        i = Integer.parseInt(date.substring(10, 12));
        calendar.set(Calendar.MINUTE, i);
        i = Integer.parseInt(date.substring(12));
        calendar.set(Calendar.SECOND, i); //设置完年／月／日／小时／分钟／秒
        return calendar.getTimeInMillis(); //转换为毫秒
    }

    private long getDateMillis(String date) {
        Calendar calendar = Calendar.getInstance();
        int i = Integer.parseInt(date.substring(0, 4));
        calendar.set(Calendar.YEAR, i);
        i = Integer.parseInt(date.substring(4, 6));
        calendar.set(Calendar.MONTH, i - 1);
        i = Integer.parseInt(date.substring(6, 8));
        calendar.set(Calendar.DAY_OF_MONTH, i);
        i = Integer.parseInt(date.substring(8, 10));
        calendar.set(Calendar.HOUR_OF_DAY, i);
        i = Integer.parseInt(date.substring(10, 12));
        calendar.set(Calendar.MINUTE, i);
        i = Integer.parseInt(date.substring(12, 14));
        calendar.set(Calendar.SECOND, i); //设置完年／月／日／小时／分钟／秒
        return calendar.getTimeInMillis(); //转换为毫秒
    }

    /**
     * 获得远程主机的当前采集时间
     *
     * @param ip
     * @return
     * @throws CollectorException
     */
    private String getRemoteCurrentTime(String ip) throws CollectorException {
        BufferedReader reader = null;
        String date = "";
        String time = "";
        try {
            reader = com.sinodata.bsm.cicp.util.CollectorUtil.getReader("date /T", ip, TIMEOUT);
            String readLine = reader.readLine();
            if (readLine != null) {
                date = readLine;
            }
            reader = com.sinodata.bsm.cicp.util.CollectorUtil.getReader("time /T", ip, TIMEOUT);
            readLine = reader.readLine();
            if (readLine != null) {
                time = readLine;
            }
        } catch (Exception e) {
            logger.error("failed to call " + this.getClass().getName() + ".getRemoteCurrentTime()", e);
            throw new CollectorException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                logger.error("failed to close BufferReader", e);
            }

        }
        return date + " " + time;
    }

    private long getRemoteCurrentTimeMillis(String ip) throws CollectorException {
        BufferedReader reader = null;
        try {
            String[] strDate = null;
            String[] sigDate = new String[3];
            String[] strTime = new String[2];
            reader = com.sinodata.bsm.cicp.util.CollectorUtil.getReader("date /T", ip, TIMEOUT);
            String readLine = reader.readLine();
            if (readLine != null) {
                strDate = readLine.split(" ");
                sigDate = strDate[0].split("-");
            }
            reader = com.sinodata.bsm.cicp.util.CollectorUtil.getReader("time /T", ip, TIMEOUT);
            readLine = reader.readLine();
            if (readLine != null) {
                strTime = readLine.trim().split(":");
                for (int i = 0; i < 2; i++) {
                    if (strTime[i].length() != 2)
                        strTime[i] = "0" + strTime[i];
                }
            }
            StringBuffer tmp = new StringBuffer().append(sigDate[0]).append(sigDate[1]).append(sigDate[2]).append(strTime[0]).append(strTime[1]).append("00");
            return getDateMillis(tmp.toString());
        } catch (Exception e) {
            logger.error("failed to call " + this.getClass().getName() + ".getRemoteCurrentTimeMillis()", e);
            throw new CollectorException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                logger.error("failed to close inputStream", ex);
                throw new CollectorException(ex);
            }
        }
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "文件名", "处理时间", "采集时间", "文件大小" };
        return new String[] { "FileName", "HandleTime", "CollectTime", "FileSize" };
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

    }

}
